Smart Pointers


Smart Pointer

A smart pointer is used to ensure that memory is released automatically when using the command new. When the smart pointer is out of scope, it is destroyed and delete is called.
Un puntero inteligente es usado para asegurar que la memoria se libera automáticamente cuando se usa el comando new. Cuando el puntero inteligente está fuera de la función dónde se creo, este se destruye y llama delete.

A smart pointer for a variable

The first program shows how to use new and delete to create an object. For this case,the programmer needs to be sure that delete is called before returning from the function. The second program illustrates how to use smart pointer to do the same. In this case, smart pointer ARE NOT necessary, because you can accomplish the same result by just using

Box box;
El primer programa muestra cómo usar new and delete para crear un objeto. Para este caso, el programado necesita asegurarse que delete es llamado antes de regresar de la función. El segundo programa ilustra cómo usar los punteros inteligente para hacer lo mismo. En este caso, los punteros inteligentes NO SON necesarios ya que se puede obtener el mismo resultado usando

Box box;

Program.h
struct Box
{
     double width;
     double height;
     double depth;
};

void Program::MyFunc()
{
     Box* box = new Box();
     Paint(*box);
     delete box;
}

void Program::Paint(const Box& box)
{
     . . .
}


Program.h
struct Box
{
     double width;
     double height;
     double depth;
};

void Program::MyFunc()
{
     std::unique_ptr<Box> box(new Box());
     Paint(*box);
}

void Program::Paint(const Box& box)
{
     . . .
}


A smart pointer for an array.

The first program shows how to use new and delete to create an array with 20 boxes. The second program illustrates how to use smart pointer to do the same.
El primer programa muestra cómo usar new and delete para crear un arreglo con 20 cajas. El segundo programa ilustra cómo usar los punteros inteligente para hacer lo mismo.

Program.h
struct Box
{
     double width;
     double height;
     double depth;
};

void Program::MyFunc()
{
     Box* box = new Box[20];
     delete [] box;
}


Program.h
struct Box
{
     double width;
     double height;
     double depth;
};

void Program::MyFunc()
{
     std::unique_ptr<Box[]> box(new Box[20]());

}


Tip
You can call the method reset of an smart pointer to release the memory at any time. You can call the method get to obtain the encapsulated pointer.
Usted puede llamar el método reset de un puntero inteligente para liberar la memoria en cualquier momento. Usted puede llamar el método get para obtener el puntero encasulado.

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home